package com.matt.service.impl;

import com.google.common.collect.Maps;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.domain.Classes;
import com.matt.domain.course.Course;
import com.matt.domain.course.CoursePlanClasses;
import com.matt.domain.course.PrepareCourse;
import com.matt.foundation.DO.course.CourseAddDO;
import com.matt.foundation.DO.course.CoursePlanClassesDO;
import com.matt.foundation.DO.course.PrepareStaffDO;
import com.matt.foundation.constant.CourseConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.query.ClassesCoursePlanQuery;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.vo.course.VendorCoursePrepareDetailVO;
import com.matt.foundation.vo.course.WebCoursePlanListVo;
import com.matt.repository.ClassesRepository;
import com.matt.repository.CourseTemplate3Repository;
import com.matt.repository.base.ClassesCoursePlanRepository;
import com.matt.repository.course.CoursePlanClassesRepository;
import com.matt.repository.course.CourseRepository;
import com.matt.repository.course.PrepareCourseRepository;
import com.matt.repository.course.PrepareTemplate3Repository;
import com.matt.repository.courseV2.VendorCourseRepository;
import com.matt.repository.courseV2.VendorPreparedCourseRepository;
import com.matt.service.CourseAuditService;
import com.matt.service.CourseService;
import com.matt.service.NoticeMessageService;
import com.matt.service.PrepareCourseService;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

;

@Service
@Slf4j
public class PrepareCourseServiceImpl implements PrepareCourseService {

    @Autowired
    private CourseTemplate3Repository courseTemplate3Repository;

    @Autowired
    private CoursePlanClassesRepository coursePlanClassesRepository;

    @Autowired
    private ClassesCoursePlanRepository classesCoursePlanRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private PrepareCourseRepository prepareCourseRepository;

    @Autowired
    private PrepareTemplate3Repository prepareTemplate3Repository;

    @Autowired
    private VendorPreparedCourseRepository vendorPreparedCourseRepository;

    @Autowired
    private VendorCourseRepository vendorCourseRepository;

    @Autowired
    private CourseAuditService courseAuditService;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    private NoticeMessageService noticeMessageService;

    @Autowired
    CourseService courseService;



    @Override
    public Page<WebCoursePlanListVo> getCourseList(ClassesCoursePlanQuery query, Boolean isTestUser) {
        if (isTestUser) {
            //外部用户，只返回前10条数据
            query.setPageNum(0);
            query.setPageSize(10);
        }
        String today = DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd");
        query.setBeginDate(today);
        query.setCourseStatus(CourseConstant.CourseStatus.STARTING.codeOf());
        List<CoursePlanClassesDO> list = classesCoursePlanRepository.findByConditions(query);
        List<WebCoursePlanListVo> voList = webFillInPlan(list);
        if (isTestUser) {
            //重新设置count
            return new PageImpl<>(voList, PageRequest.of(query.getPageNum(), query.getPageSize()), voList.size());
        }
        Long count = classesCoursePlanRepository.countByConditions(query);
        return new PageImpl(voList, PageRequest.of(query.getPageNum(), query.getPageSize()), count);
    }

    @Override
    public Page<WebCoursePlanListVo> getWebCoursePlanHistory(ClassesCoursePlanQuery query, Boolean isTestUser) {
        if (isTestUser) {
            //外部用户，只返回前10条数据
            query.setPageNum(0);
            query.setPageSize(10);
        }
        String today = DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd");
        query.setEndDate(today);
        List<CoursePlanClassesDO> classesPlanList = classesCoursePlanRepository.findHistoryByCondition(query);
        List<WebCoursePlanListVo> voList = webFillInPlan(classesPlanList);
        if (isTestUser) {
            //重新设置count
            return new PageImpl<>(voList, PageRequest.of(query.getPageNum(), query.getPageSize()), voList.size());
        }

        Long count = classesCoursePlanRepository.countHistoryByCondition(query);
        return new PageImpl(voList, PageRequest.of(query.getPageNum(), query.getPageSize()), count);
    }

    public List<WebCoursePlanListVo> webFillInPlan(List<CoursePlanClassesDO> planNurseryClassesList) {
        List<WebCoursePlanListVo> voList = Lists.newArrayList();
        for (CoursePlanClassesDO plan : planNurseryClassesList) {
            PrepareCourse prepareCourse = prepareCourseRepository.findByCoursePlanClassesId(plan.getClassesCoursePlanId());
            WebCoursePlanListVo vo = WebCoursePlanListVo.of(plan, plan.getClassesName(), prepareCourse);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public Map courseDetail(String areaId, String coursePlanClassesId) {
        Map response = new HashMap();
        CoursePlanClasses coursePlanClasses = coursePlanClassesRepository.getOne(coursePlanClassesId);
        if (Objects.isNull(coursePlanClasses))
            throw new BusinessException(ErrorCode.COURSE_NOT_EXISTD, "该课程未备课");
        Classes classes = classesRepository.getOne(coursePlanClasses.getClassesId());
       // VendorCourse course = vendorCourseRepository.getOne(coursePlanClasses.getCourseId());
        //Course course = courseRepository.getOne(coursePlanClasses.getCourseId());
//        if (Objects.isNull(course))
//            throw new BusinessException(ErrorCode.COURSE_NOT_EXISTD, "该课程不存在");

        //TODO 查看是否需要审核
        Boolean hasAuditor = courseAuditService.needAudit(coursePlanClasses.getAreaId(), coursePlanClasses.getCategory());
        response.put("hasAuditor", hasAuditor);

        PrepareCourse prepareCourse = prepareCourseRepository.findByCoursePlanClassesId(coursePlanClasses.getId());
        response.put("coursePlanClasses", coursePlanClasses);
        if (CourseConstant.CourseType.AREA_BUILD.codeOf() == coursePlanClasses.getCourseType()) {
            response.put("course",  courseService.getCourseAreaBuildByCourseId(areaId, coursePlanClasses.getCourseId())) ;
//            CourseTemplateAreaBuild prepareTemplate = prepareTemplate3Repository.getOne(prepareCourse.getPrepareTemplateId());
//            response.put("prepareTemplate", prepareTemplate);
        }else if (CourseConstant.CourseType.SAT.codeOf() == coursePlanClasses.getCourseType()) {
            response.put("course",vendorCourseRepository.getOne(coursePlanClasses.getCourseId()));
//            VendorPreparedCourse prepareTemplate = vendorPreparedCourseRepository.getOne(prepareCourse.getPrepareTemplateId());
//            response.put("prepareTemplate", prepareTemplate);
        }
        response.put("classesName", classes.getName());
        response.put("prepareCourse", prepareCourse);
        if (Objects.isNull(prepareCourse))
            return response;


        return response;
    }
    private Map buildCoursePlanDetail(String name,Object object) {
        Map result = Maps.newHashMap();
        result.put("name",name);
        result.put("courserangetable",object);
        return result;
    }

    @Transactional
    @Override
    public Boolean prepareCourse(StaffDTO staff, VendorCoursePrepareDetailVO prepareDetail, String coursePlanClassesId, Integer action){
        CoursePlanClasses coursePlanClasses = coursePlanClassesRepository.getOne(coursePlanClassesId);
        coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.PREPARED.codeOf());

        Boolean hasAuditor = courseAuditService.needAudit(coursePlanClasses.getAreaId(), coursePlanClasses.getCategory());//sso库  area_setting设置的 是否开启一些列审核。
        if (2 == action) {//提交审核
            if (!hasAuditor){
                //throw new BusinessException(ErrorCode.HAS_NOT_AUDITOR, "没有设置审核人");
                coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.APPROVED.codeOf());
            }else{
                coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.NON_AUDIT.codeOf());
                noticeMessageService.generateKXThemeCourseAudit(coursePlanClassesId);
            }
        }else
        if (1 == action) {  //备课
            coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.PREPARED.codeOf());
        }

        PrepareCourse prepareCourse = prepareCourseRepository.findByCoursePlanClassesId(coursePlanClasses.getId());

        //不存在备课信息
        if (Objects.isNull(prepareCourse)) {
            //创建备课条目
            prepareCourse = PrepareCourse.of(prepareDetail,coursePlanClassesId, coursePlanClasses.getCourseId(), coursePlanClasses.getCourseName(), coursePlanClasses.getTypeName(),
                    coursePlanClasses.getCourseType(), staff.getId(), staff.getRealName());
            prepareCourseRepository.save(prepareCourse);

            // 创建备课对象
//          //  if(CourseConstant.Template.KX_THEME.codeOf() == prepareCourse.getTemplateType()) {
//                //TODO: 创建备课备课信息
//                VendorPreparedCourse vendorPreparedCourse = VendorPreparedCourse.of(prepareDetail);
//                vendorPreparedCourseRepository.save(vendorPreparedCourse);
//
//                // 更新备课id
//                prepareCourse.setPrepareTemplateId(vendorPreparedCourse.getId());
//                prepareCourseRepository.save(prepareCourse);
//        //    }
        } else {
            //已经存在备课信息，更新修改时间
            prepareCourse.setLastModified(new Date());
            prepareCourse.setLastModifiedId(staff.getId());
            prepareCourse.setLastModifiedName(staff.getRealName());
            if (CourseConstant.Template.KX_THEME.codeOf() == prepareCourse.getTemplateType()) {
            }
        }

        return true;
    }


    private void saveTemplate3(PrepareCourse prepareCourse, CourseAddDO courseAddDO, StaffDTO dto) {
        Course one = courseRepository.getOne(courseAddDO.getCourseId());
        courseAddDO.setAreaId(one.getAreaId());
        courseAddDO.setCreateStaffId(one.getCreateStaffId());
        courseAddDO.setCreateStaffName(one.getCreateStaffName());
        courseAddDO.setHelpStaffId(one.getHelpStaffId());
        courseAddDO.setHelpStaffName(one.getHelpStaffName());
        prepareCourse.setPrepareTemplateId(one.getCourseTemplateId());
        prepareCourseRepository.saveAndFlush(prepareCourse);
        courseService.createCourseByCommonTemplete(null, courseAddDO, dto);
    }

    @Override
    public Long nonPrepareCount(String staffId, String areaId) {
        ClassesCoursePlanQuery query = new ClassesCoursePlanQuery();
        query.setStaffId(staffId);
        query.setAreaId(areaId);
        query.setBeginDate(DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd"));
        query.setPrepareStatus(CourseConstant.PrepareStatus.NON_PREPARE.codeOf());
        query.setType("today");
        Long count = classesCoursePlanRepository.countByConditions(query);
        return count;
    }

    @Override
    public List<PrepareStaffDO> getCoursePlanClassList(String areaId,String today) {
        ClassesCoursePlanQuery query = new ClassesCoursePlanQuery();
        query.setAreaId(areaId);
        query.setBeginDate(today);
        query.setType("today");

        List<PrepareStaffDO> coursePlanClassList = classesCoursePlanRepository.getCoursePlanClassList(query);

        return coursePlanClassList;
    }

    @Override
    public Boolean prepareAreaBuildCourse(StaffDTO dto,VendorCoursePrepareDetailVO prepareDetail, String coursePlanClassesId, String content, Integer action,
                                          CourseAddDO courseAddDO) {
        CoursePlanClasses coursePlanClasses = coursePlanClassesRepository.getOne(coursePlanClassesId);
        Boolean hasAuditor = courseAuditService.needAudit(coursePlanClasses.getAreaId(), coursePlanClasses.getCategory());//sso库  area_setting设置的 是否开启一些列审核。

        coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.PREPARED.codeOf());
        //提交审核
        if (2 == action) {
            if (!hasAuditor){
                coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.APPROVED.codeOf());
            }else{
                coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.NON_AUDIT.codeOf());
                noticeMessageService.generateAreaBuildCourseAudit(coursePlanClassesId);
            }

        }
        if (1 == action) {
            coursePlanClasses.setPrepareStatus(CourseConstant.PrepareStatus.PREPARED.codeOf());
        }


        PrepareCourse prepareCourse = prepareCourseRepository.findByCoursePlanClassesId(coursePlanClasses.getId());


        if (Objects.isNull(prepareCourse)) {

            //创建备课条目
            prepareCourse = PrepareCourse.of(prepareDetail,coursePlanClassesId, coursePlanClasses.getCourseId(), coursePlanClasses.getCourseName(), coursePlanClasses.getTypeName(),
                    coursePlanClasses.getCourseType(), dto.getId(), dto.getRealName());
            prepareCourseRepository.save(prepareCourse);


        } else {
            prepareCourse.setLastModified(new Date());
            prepareCourse.setLastModifiedId(dto.getId());
            prepareCourse.setLastModifiedName(dto.getRealName());

        }

        return true;
    }

    @Override
    public Map coursePADDetail(String areaId, String coursePlanClassesId) {
        return courseDetail(areaId, coursePlanClassesId);
    }

}
